package com.diamond.facade;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.diamond.action.Page;
import com.diamond.bo.InlayDiaPicBO;
import com.diamond.bo.InlayDiamonBO;
import com.diamond.bo.QueryInlayDiamondBO;
import com.diamond.bo.ReturnBO;
import com.diamond.entity.TInlayDiaPic;
import com.diamond.entity.TInlayDiaPrice;
import com.diamond.entity.TInlayDiamond;
import com.diamond.service.IInlayDiamondService;
import com.diamond.util.StringUtil;
import com.diamond.util.UploadUtil;
import com.opensymphony.xwork2.ActionContext;

public class InlayDiamondFacade extends CommonFacade<InlayDiamonBO> {
	public IInlayDiamondService inlayDiamondService;

	public void setInlayDiamondService(IInlayDiamondService inlayDiamondService) {
		this.inlayDiamondService = inlayDiamondService;
	}
	
	public void save(InlayDiamonBO bo, List<TInlayDiaPic> picList) {
		if(bo==null)return;
		TInlayDiamond entity = new TInlayDiamond();
		try {
			PropertyUtils.copyProperties(entity, bo);
			TInlayDiamond t=(TInlayDiamond) service.merge(entity);
			String inlayDiaId=t.getInlayDiamondId().toString();
			for(TInlayDiaPic pic :picList){
				pic.setInlayDiamondId(inlayDiaId);
				service.save(pic);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void upLoadMainPic(File file,String userForder,String fileName) {
		String picForder=UploadUtil.getPicForder();
		File imageFile = new File(picForder+"/"+userForder+"/"+fileName);
		UploadUtil.copy(file, imageFile);
	}
	
	public TInlayDiaPic upLoadOtherPic(File file,String userForder,String fileName) {
		upLoadMainPic(file,userForder,fileName);
		TInlayDiaPic inlayDiaPic= new TInlayDiaPic();
		inlayDiaPic.setPicLine(userForder+"/"+fileName);
		inlayDiaPic.setPicName(fileName);
		return inlayDiaPic;
	}
	
	public Object[] toMyInlayDia(HttpServletRequest request, Map session) {
		String url="tomyinlaydia.action?a=1";
		Object userId= session.get("USER_ID");
		
		String inlayRate="";
		String sql="select rate from t_inlay_dia_price where user_id="+userId;
		List tmpList=inlayDiamondService.findBySQL(sql);
		if(tmpList!=null&&tmpList.size()>0)inlayRate=tmpList.get(0).toString();
		
		sql="select * from t_inlay_diamond where user_id="+userId;
		List list = Page.stageUtil(InlayDiamonBO.class, request, url, this, sql,20);
		
		return new Object[]{list,inlayRate};
	}
	
	public Object[] toSupInlayDia(HttpServletRequest request, Map session) {
		String url="tosupinlaydia.action?a=1";
		Object userId= session.get("USER_ID");
		Object userType= session.get("USER_TYPE");
		Object angentId= session.get("ANGENT_ID");
		
		String inlayRate="";
		String sql="select rate from t_inlay_dia_price where user_id="+userId;
		List tmpList=inlayDiamondService.findBySQL(sql);
		if(tmpList!=null&&tmpList.size()>0)inlayRate=tmpList.get(0).toString();
		
		if("B".equals(userType)){
			sql="select *,1 as rate from t_inlay_diamond where inlay_level='A'";
		}else if("C".equals(userType)){
			String angentRate="1";
			if(angentId!=null){
				sql="select rate from t_inlay_dia_price where user_id="+angentId;
				tmpList=inlayDiamondService.findBySQL(sql);
				if(tmpList!=null&&tmpList.size()>0)angentRate=tmpList.get(0).toString();
			}
			
			sql="select *,if(inlay_level='A',"+angentRate+",1) as rate from t_inlay_diamond where inlay_level='A' or user_id="+angentId;
		}
		List<InlayDiamonBO> list = Page.stageUtil(InlayDiamonBO.class, request, url, this, sql,20);
		if(list==null)return null;
		List<InlayDiamonBO> list1 = new ArrayList<InlayDiamonBO>(); 
		for (InlayDiamonBO bo : list){
			Double rate = bo.getRate();
			Double k18Price=bo.getK18Price()!=null?bo.getK18Price():0d;
			Double pt900Price=bo.getPt900Price()!=null?bo.getPt900Price():0d;
			Double pt950Price=bo.getPt950Price()!=null?bo.getPt950Price():0d;
			bo.setK18Price(k18Price*rate);
			bo.setPt900Price(pt900Price*rate);
			bo.setPt950Price(pt950Price*rate);
			list1.add(bo);
		}
		return new Object[]{list1,inlayRate};
	}

	public Integer editRate(Object userId,String inlayRate) {
		
		TInlayDiaPrice inlayDiaPrice = new TInlayDiaPrice();
		inlayDiaPrice.setUserId((Long) userId);
		inlayDiaPrice.setRate(Double.valueOf(inlayRate));
		try {
			inlayDiamondService.updateBySQL("delete from t_inlay_dia_price where user_id="+userId);
			inlayDiamondService.save(inlayDiaPrice);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	public String getRate(Object userid) {
		String rate="1";
		if(userid==null)return rate;
		String sql="select rate from t_inlay_dia_price where user_id="+userid;
		inlayDiamondService.findBySQL(sql);
		List tmpList=inlayDiamondService.findBySQL(sql);
		if(tmpList!=null&&tmpList.size()>0)rate=tmpList.get(0).toString();
		return rate;
	}

	public void delInlayDia(Object userId, String inlayDiaId) {
		if(userId==null)return;
		String sql="delete from t_inlay_diamond where inlay_diamond_id="+inlayDiaId+" and user_id="+userId;
		inlayDiamondService.updateBySQL(sql);
		sql="delete from t_inlay_dia_pic where inlay_diamond_id="+inlayDiaId;
		inlayDiamondService.updateBySQL(sql);
		
	}

	public List listInlay(HttpServletRequest request, Map session,
			InlayDiamonBO inlayDiamondBo) {
		String orderNo=request.getParameter("orderNo");
		if(orderNo!=null){
			session.put("orderNo",orderNo);
		}
		String batch=request.getParameter("batch");
		if(batch!=null){
			session.put("batch",batch);
		}
		String url="toinlay.action?a=1";
		String type=(String) session.get("USER_TYPE");
		Object angentId=session.get("ANGENT_ID");
		Object userId=session.get("USER_ID");
		String priceSQL = "";
		if("C".equals(type)){
			priceSQL=builPriceSQL(session.get("USER_ID"),angentId,1);
		}else if("B".equals(type)){
			priceSQL=builPriceSQL(session.get("USER_ID"),angentId,2);
		}
		String HQL="select *,"+priceSQL+"as price from t_inlay_diamond where (inlay_level='A' ";
		if(userId!=null && null == angentId) {
			HQL+="or user_id="+userId+") ";
		} else if (userId != null && angentId != null) {
			HQL+="or user_id in ("+userId+","+angentId+"))";
		} else if (null == userId && angentId != null) {
			HQL+="or user_id=" + angentId + ") ";
		} else if (null == userId && null == angentId) {
			HQL+=")";
		}
		
		if(inlayDiamondBo!=null){
			if(!StringUtils.isEmpty(inlayDiamondBo.getInlayType())){
				url+="&inlayDiamondBo.inlayType="+inlayDiamondBo.getInlayType();
				HQL+=" and inlay_type='"+inlayDiamondBo.getInlayType()+"'";
			}
			if(!StringUtils.isEmpty(inlayDiamondBo.getInlayNumber())){
				url+="&inlayDiamondBo.inlayNumber="+inlayDiamondBo.getInlayNumber();
				HQL+=" and inlay_number="+inlayDiamondBo.getInlayNumber();
			}
			if(!StringUtils.isEmpty(inlayDiamondBo.getMinPrice())){
				url+="&inlayDiamondBo.minPrice="+inlayDiamondBo.getMinPrice();
				HQL+=" and "+priceSQL+">="+inlayDiamondBo.getMinPrice();
			}
			if(!StringUtils.isEmpty(inlayDiamondBo.getMaxPrice())){
				url+="&inlayDiamondBo.maxPrice="+inlayDiamondBo.getMaxPrice();
				HQL+=" and "+priceSQL+"<="+inlayDiamondBo.getMaxPrice();
			}
			if(!StringUtils.isEmpty(inlayDiamondBo.getInlayName())){
				try {
					String name=URLDecoder.decode(inlayDiamondBo.getInlayName(),"UTF-8");
					inlayDiamondBo.setInlayName(name);
					url+="&inlayDiamondBo.inlayName="+name;
					HQL+=" and inlay_name like '%"+name+"%'";
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
			}
		}
//		System.out.println(HQL);
		return Page.stageUtil(InlayDiamonBO.class, ServletActionContext.getRequest(), url, this, HQL,12);
	}
	
	public Object[] toInlayDetail(HttpServletRequest request, Map session) {
		String id=request.getParameter("inlayDiamondId");
		if(!StringUtils.isEmpty(id)){
			try {
				TInlayDiamond rang=(TInlayDiamond) findById(new Long(id));
				InlayDiamonBO inlayDiamondBo = new InlayDiamonBO();
				PropertyUtils.copyProperties(inlayDiamondBo, rang);
				String diaBatch=(String) ActionContext.getContext().getSession().get("batch");
				if(diaBatch!=null)inlayDiamondBo.setDiaBatch(diaBatch);
				Object userId=session.get("USER_ID");
				Object angentId=session.get("ANGENT_ID");
				String type=(String) session.get("USER_TYPE");
				Double angentRate=Double.parseDouble(getRate(angentId));
				Double userRate=1d;
				if("C".equals(type)){
					userRate=Double.parseDouble(getRate(userId));
				}
				String inlayLevel=inlayDiamondBo.getInlayLevel();
				Double rate = null;
				if("A".equals(inlayLevel)){
					rate= angentRate*userRate;
				}else if("B".equals(inlayLevel)){
					rate= userRate;
				}else if("C".equals(inlayLevel)){
					rate= 1d;
				}
				inlayDiamondBo.setRate(rate);
				Double k18Price=inlayDiamondBo.getK18Price()!=null?inlayDiamondBo.getK18Price():0d;
				Double pt900Price=inlayDiamondBo.getPt900Price()!=null?inlayDiamondBo.getPt900Price():0d;
				Double pt950Price=inlayDiamondBo.getPt950Price()!=null?inlayDiamondBo.getPt950Price():0d;
				inlayDiamondBo.setK18Price(k18Price*rate);
				inlayDiamondBo.setPt900Price(pt900Price*rate);
				inlayDiamondBo.setPt950Price(pt950Price*rate);
				
				List list = findByHQL("from TInlayDiaPic where inlayDiamondId="+id);
				return new Object[]{inlayDiamondBo,list};
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private String builPriceSQL(Object userId,Object angentId,Integer type){
		String userRate=getRate(userId);
		String angentRate=getRate(angentId);
		String sql="";
		if(1==type){
			sql="k18_price*if(inlay_level='A',"+angentRate+"*"+userRate+",if(inlay_level='B'," +
			   userRate+",1))";
		}else if(2==type){
			sql="k18_price*if(inlay_level='A',"+angentRate+",1)";
		}
		return sql;
	}

/**-------------------------------------------------------------------------------------------------------------------------*/
	
	public Boolean saveInlayDiamond(InlayDiamonBO inlayDiamondBo, List<InlayDiaPicBO> inlayDiaPicBolist) {
		Boolean result = false;
		List<TInlayDiaPic> piclist = new ArrayList<TInlayDiaPic>();
		try {
			for (InlayDiaPicBO inlayDiaPicBo : inlayDiaPicBolist) {
				TInlayDiaPic tInlayDiaPic = new TInlayDiaPic();
				if (!StringUtil.isEmpty(inlayDiamondBo.getInlayDiamondId()) && inlayDiamondBo.getInlayDiamondId() > 0) {
					this.delInlayDiamond(inlayDiamondBo.getInlayDiamondId().toString());
				}
				PropertyUtils.copyProperties(tInlayDiaPic, inlayDiaPicBo);
				piclist.add(tInlayDiaPic);
			}
			this.save(inlayDiamondBo, piclist);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return result;
	}
	
	public ReturnBO<InlayDiamonBO> queryInlayDiamondList(QueryInlayDiamondBO queryInlayDiamondBo) throws Exception {
		return inlayDiamondService.queryInlayDiamondList(queryInlayDiamondBo);
	}

	public InlayDiamonBO queryInlayDiamondDetail(String inlayDiaId)throws Exception {
		return inlayDiamondService.queryInlayDiamondDetail(inlayDiaId);
	}

	public Boolean updateInlayDiamond(InlayDiamonBO inlayDiamondBo) throws Exception {
		return inlayDiamondService.updateInlayDiamond(inlayDiamondBo);
	}

	public List<InlayDiaPicBO> queryInlayDiamondPic(String inlayDiaId) throws Exception {
		List<InlayDiaPicBO> list = inlayDiamondService.queryInlayDiamondPic(inlayDiaId);
		for (InlayDiaPicBO inlayDiaPicBo : list) {
			inlayDiaPicBo.setPicLine(UploadUtil.getPicWeb()+"/"+inlayDiaPicBo.getPicLine());
		}
		return list;
	}

	public void delInlayDiamond(String inlayDiaId) {
		inlayDiamondService.delInlayDiamond(inlayDiaId);
	}
	
}
